package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zx
 * @date 2021/11/18 10:18
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    /**
     * 登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDTO dto) {
        //1 参数校验
        if (StringUtils.isBlank(dto.getName())|| StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"参数错误");
        }

        //2 查询用户是否存在
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery()
                .eq(AdUser::getName, dto.getName())
        );

        //3.1从数据库中获取密码和盐
        String dbPwd = adUser.getPassword();
        String adSalt = adUser.getSalt();

        //3.2密码+盐生成新的密码
        String adPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + adSalt).getBytes());

        //3.3将新的密码与加密后的密码进行比较
        if (! dbPwd.equals(adPwd)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"密码错误");
        }
        //4.检查用户状态
        if(! adUser.getStatus().equals(9)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户状态异常，请联系管理员");
        }

        //5.更新登录时间
        adUser.setLoginTime(new Date());
        updateById(adUser);
        //6颁发jwt
        String token = AppJwtUtil.getToken(adUser.getId().longValue());

        //7用户信息返回vo
        AdUserVO adUserVO=new AdUserVO();
        BeanUtils.copyProperties(adUser,adUserVO);

        Map<String, Object> map = new HashMap<>();
        map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
        //密码和盐值不能返给用户
        adUser.setPassword("");
        adUser.setSalt("");

        map.put("user",adUserVO);

        System.out.println("登录成功");
        return ResponseResult.okResult(map);

    }
}
